package org.oschina.api.blog.order.service;

import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.blog.order.dao.BlogOrderDAO;
import org.oschina.api.blog.order.model.BlogOrder;
import org.oschina.api.blog.order.vo.BlogOrderVo;
import org.oschina.api.index.service.IndexService;
import org.oschina.bean.Result;
import org.oschina.security.ISecurity;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BlogOrderService extends BaseService {

	@Autowired
	private BlogOrderDAO orderDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private ISecurity security;
	
	/**
	 * 创建
	 * @param order
	 * @return
	 */
	@Require(authorization=Module.MODULE_38)
	public Result create(BlogOrder order)
	{
		return ResultUtil.getSuccess(_create(order));
	}
	
	/**
	 * 更新
	 * @param order
	 * @return
	 */
	@Require(authorization=Module.MODULE_38)
	public Result update(BlogOrder order)
	{
		if(_update(order)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(order);
	}
	
	/**
	 * 返回
	 * @return
	 */
	public List<BlogOrderVo> findVo()
	{
		List<BlogOrderVo> result=_findVo();
		if(!security.require(new String[]{Module.MODULE_38}, getToken(), false))
		{
			for(BlogOrderVo order:result)
			{
				order.setCreate_time(null);
				order.setIndex(null);
			}
		}
		return result;
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public BlogOrderVo _findVoById(int id)
	{
		return orderDAO.findVoById(id);
	}
	
	/**
	 * 返回
	 * @return
	 */
	private List<BlogOrderVo> _findVo()
	{
		return orderDAO.findVo();
	}
	
	/**
	 * 创建
	 * @param order
	 * @return
	 */
	private BlogOrder _create(BlogOrder order)
	{
		order.setId(_getIndex());
		order.setCreate_time(DateUtil.now());
		return orderDAO.create(order);
	}
	
	/**
	 * 更新
	 * @param order
	 * @return
	 */
	private int _update(BlogOrder order)
	{
		return orderDAO.update(order);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_BLOG_ORDER);
	}
}